const path = require('path');
const mongoose = require('mongoose');

// 数据库连接函数
// const connectDB = () => {
//   return mongoose.connect('mongodb://admin:admin@47.109.189.194:27017/jinx')
//     .then(() => console.log('Connected to MongoDB'))
//     .catch(err => console.error('Connection error', err));
// };
let dbConnection;
const connectDB = async () => {
  if (dbConnection) {
    return dbConnection;
  }

  const uri = process.env.MONGO_URI || 'mongodb://admin:admin@47.109.189.194:27017/jinx';
  try {
    dbConnection = await mongoose.connect(uri, {});
    console.log('数据库 已连接');
    return dbConnection;
  } catch (error) {
    console.error('数据库连接错误:', error);
    process.exit(1);
  }
};

// 获取当前文件名（不带扩展名）
// const name = () => {
//   if (module.parent) {
//     const callerFilePath = module.parent.filename;
//     return path.basename(callerFilePath, path.extname(callerFilePath));
//   }
//   return null; // 如果当前模块是顶层模块，返回 null
// }

// const name = () => {
//   const stack = new Error().stack.split('\n');
//   const callerLine = stack[2].trim(); // 第二行是调用者的信息
//   const match = callerLine.match(/\((.*):\d+:\d+\)/);
//   if (match) {
//     const callerFilePath = match[1];
//     return path.basename(callerFilePath, path.extname(callerFilePath));
//   }
//   return 'unknown';
// };

const name = (callerFilePath) => {
  if (callerFilePath) {
    return path.basename(callerFilePath, path.extname(callerFilePath));
  }
  if (module.parent) {
    const callerFilePath = module.parent.filename;
    return path.basename(callerFilePath, path.extname(callerFilePath));
  }
  return null; // 如果当前模块是顶层模块，返回 null
};

// const name = path.basename(__filename, path.extname(__filename))

// 动态加载模型
const items = (nnn) => {
  const modelName = name(nnn);
  const modelPath = path.resolve(__dirname, '../../models', modelName);
  // console.log('Model path:', modelPath); // 输出路径，确保路径正确
  return require(modelPath);
}
/**
 * 
 * @param {上下文} ctx 
 * @param {返回结果} res 
 * @param {总数} total 
 * @param {状态码} code 
 * @param {提示信息} msg 
 * @returns 
 */
const response = (ctx, res, total, code, msg) => {
  ctx.response.body = {
    code: code || 200,
    msg: msg || '操作成功',
    data: res,
  };
  if (total !== undefined) {
    ctx.response.body.total = total;
  }
  if (res) {
   return  ctx.response.body
  } else {
    return ctx.response.body = {
      code: code || 1001,
      msg: msg || '操作失败',
      data: res
    };
  }
}

module.exports = {
  connectDB,
  name,
  items,
  response
};